﻿using System;
using System.Collections.Generic;
using System.Linq;
using BigData.DataContracts.Objects.BigData;
using Twitterizer;
using BigData.DataContracts.Objects.Twitter;
using MongoDB.Bson;
using System.Globalization;

namespace BigDataFramework.Library.Objects.DataAdapters.Twitter
{
    public class TwitterDataAdapter : DataAdapterBase<BigDataTwitterTweet>
    {
        OAuthTokens tokens;

        public TwitterDataAdapter()
        {
            // TODO: Retrieve this from elsewhere (it's currently hardcoded for Gilligan)
            tokens = new OAuthTokens();
            tokens.ConsumerKey = "DR8zlcbRkgsoxagMxhr99g";
            tokens.ConsumerSecret = "BN87eSRGI3AjmYKKLUMCv1SKhYp3JiV4XDYoEjwOJp4";
            tokens.AccessToken = "824516922-wkRRZs9BwSn6WtuTA5rlODiJkA1710MLqj23C4pe";
            tokens.AccessTokenSecret = "rzTEbCoT2CA5mCQSbcAsiC4ZNJT5egmrvee2UNHa8";
        }

        protected override List<BigDataTwitterTweet> RetrieveDataFromAPIForUser(BigDataUser user, DateTime startDate, DateTime endDate)
        {
            DateTime tweetedDate;

            UserTimelineOptions u = new UserTimelineOptions();
            u.SinceStatusId = 0;

            TwitterResponse<TwitterStatusCollection> response = TwitterTimeline.UserTimeline(tokens, u);
            List<BigDataTwitterTweet> tweets = new List<BigDataTwitterTweet>();
            if (response.ErrorMessage == "Unable to parse JSON")
            {
                dynamic json = SimpleJson.DeserializeObject(response.Content);
                foreach (dynamic tweet in json)
                {
                    tweetedDate = DateTime.ParseExact(tweet["created_at"], "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);
                    tweetedDate = DateTime.SpecifyKind(tweetedDate, DateTimeKind.Utc);

                    tweets.Add(
                        new BigDataTwitterTweet()
                        {
                            TweetData = tweet,
                            RecordStartDate = DateTime.Now,
                            RecordEndDate = DateTime.MaxValue,
                            AssociatedUserIds = new List<string>{user._id},
                            TweetedDate = tweetedDate
                        }
                    );
                }
            }
            else
            {
                throw new Exception(response.ErrorMessage);
            }

            return tweets.Where(twt => twt.TweetedDate > startDate && twt.TweetedDate <= endDate).ToList();
        }

        public override Event ConvertObjToEvent(BigDataTwitterTweet obj)
        {
            Event output = new Event()
            {
                AffiliatedUserIds = obj.AssociatedUserIds.Select<string, ObjectId>(uid => ObjectId.Parse(uid)).ToList(),

                Headline = "Tweet",
                Text = obj.TweetData["text"],
                StartDate = obj.TweetedDate,
                EndDate = obj.TweetedDate,

                RegisteredCollectionId = this.RegisteredCollectionId,
                RegisteredCollectionObjectId = ObjectId.Parse(obj._id),

                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            return output;
        }
    }
}
